<?php

function truncate( $string, $len = 40, $dots = TRUE )
{
	$retVal = $string;

  	/*
  	 * get current encoding:
  	 * "auto" is expanded to: ASCII,JIS,UTF-8,EUC-JP,SJIS
  	 */

  	$encoding = mb_detect_encoding( $string, "auto" );

  	// leng of string in current encoding
  	$strlen = mb_strlen( $string, $encoding );

  	$delta = $strlen - $len;
  	if ( $delta > 0 )
  	{
   		$shortText = "";

    	// trim it by length in current encoding
    	$shortText = mb_substr($string, 0, $len, $encoding);

    	// find the last break word
    	$breakPos = $len;
    	$breakPatten = array(" ", ",", ".", ":", "_", "-", "+");
    	foreach( $breakPatten as $id => $breakKey )
    	{
    		if( mb_strrpos($shortText, $breakKey, $encoding) )
			{
				if( $id==0 ) {
					$breakPos = mb_strrpos( $shortText, $breakKey, $encoding );
				} else {
					$breakPos = ( $breakPos > mb_strrpos( $shortText, $breakKey, $encoding ) ) ? $breakPos : mb_strrpos( $shortText, $breakKey, $encoding );
				}
			}
		}

    	//remove break word
    	$shortText = mb_substr( $shortText, 0, $breakPos, $encoding );

    	if ($dots) $shortText .= "...";

    	$retVal = $shortText;
  	}

  	return $retVal;
}

function makeNewsThumbnailUrl($id, $version = 0) {
    $config = Vega_App::getInstance()->coreConfig;
    if ($version > 0)
        return $config['static']['data_url'] . $config['static']['news'] . "/$id.jpg?v=$version";
    else
        return $config['static']['data_url'] . $config['static']['news'] . "/$id.jpg";
}

function makeChannelThumbnailUrl($id, $version) {
    $config = Vega_App::getInstance()->coreConfig;
    return $config['static']['data_url'] . $config['static']['channel'] . "/$id.jpg?v=$version";
}

function makeChannelCatThumbnailUrl($id, $version) {
    $config = Vega_App::getInstance()->coreConfig;
    return $config['static']['data_url'] . $config['static']['channelcat'] . "/$id.jpg?v=$version";
}

function makeBannerImageLink($image) {
	$config = Vega_App::getInstance()->coreConfig;
	return $config['static']['data_url'] . $config['static']['banner'] ."/". $image;
}

function timeFormat($time)
{
	$datetime = date_parse($time);
    if ($datetime['minute'] < 10) $datetime['minute'] = 0 . $datetime['minute'];
    if ($datetime['second'] < 10) $datetime['second'] = 0 . $datetime['second'];
	return $datetime['hour'] . ':' . $datetime['minute'] . ':' . $datetime['second'] . ' ' . $datetime['day'] . '/' . $datetime['month'] . '/' . $datetime['year'];
}

function secondToTime($s)
{
	$hour = floor($s / 3600);
	$minute = floor(($s - $hour * 3600) / 60);
	$second = $s - $hour * 3600 - $minute * 60;

	if($hour == 0) {
		$hour = '';
	}else if($hour < 10) {
		$hour = '0'.$hour.':';
	}else {
		$hour = $hour.':';
	}

	if($minute == 0) {
		$minute = '00:';
	}else if($minute < 10) {
		$minute = '0'.$minute.':';
	}else {
		$minute = $minute.':';
	}

	if($second == 0) {
		$second = '00';
	}else if($second < 10) {
		$second = '0'.$second;
	}

	return $hour.$minute.$second;
}

/****************
 * Clip helper
 ***************/
function parseEmbedParam($param) {
	$arrParam = array();
	if ($param & AUTOPLAY) $arrParam[] = 'a';
	if ($param & WATERMARK) $arrParam[] = 'wm';

	$arrParam = implode(',',$arrParam);
    $arrParam = ($arrParam) ? ',' . $arrParam : $arrParam;
}

//FlashVars version, use to optimize request
function renderPlayer($clip, $width=448, $height=372) {
	$config = Vega_App::getInstance()->coreConfig;
    $clipId         = $clip['id'];
    $protocol 		= "http";
	$serverAdress	= isset($config['streaming']['server'])? $config['streaming']['server'] : $clip['streaming_server'];
    $mediaPath      = $clip['directory'] . storageSolutionEncode1($clipId) . '/' . $clipId;
    $extension      = "mp4";
    $videoUrl =     "$protocol://$serverAdress/$mediaPath/$clipId.$extension";
    $previewUrl     = makeLargeVideoThumbnailUrl($clipId, $clip['thumbnail_version']);

    $html = "<script type='text/javascript' src='/js/swfobject.js'></script>

            <div id='player'><a href=\"http://get.adobe.com/flashplayer\">Get Flash</a> to see this player.</div>

            <script type='text/javascript'>
              var so = new SWFObject('/swf/player.swf','ply','$width','$height','9','#ffffff');
              so.addParam('allowfullscreen','true');
              so.addParam('allowscriptaccess','always');
              so.addParam('wmode','transparent');
              so.addVariable('file','$videoUrl');
              so.addVariable('image','$previewUrl');
              so.addVariable('skin','/swf/modieus.swf');
              so.write('player');
            </script>";

	return $html;
}

//FlashVars version, use to optimize request
function renderPlayer2($clip, $width=448, $height=372) {
	$config = Vega_App::getInstance()->coreConfig;
    $clipId         = $clip['id'];
    $protocol 		= "http";
	$serverAdress	= isset($config['streaming']['server'])? $config['streaming']['server'] : $clip['streaming_server'];
    $mediaPath      = $clip['directory'] . storageSolutionEncode1($clipId) . '/' . $clipId;
    $extension      = "mp4";
    $videoUrl       = "$protocol://$serverAdress/$mediaPath/$clipId.$extension";
    $previewUrl     = makeLargeVideoThumbnailUrl($clipId, $clip['thumbnail_version']);

    $html = "<script type='text/javascript' src='/js/swfobject.js'></script>
    <script type=\"text/javascript\">
		swfobject.registerObject(\"player\",\"9.0.98\",\"/swf/expressInstall.swf\");
	</script>

	<object id=\"player\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" name=\"player\" width=\"$width\" height=\"$height\">
		<param name=\"movie\" value=\"/swf/player.swf\" />
		<param name=\"allowfullscreen\" value=\"true\" />
		<param name=\"allowscriptaccess\" value=\"always\" />
        <param name=\"wmode\" value=\"transparent\" />
		<param name=\"flashvars\" value=\"file=$videoUrl&image=$previewUrl&skin=/swf/modieus.swf\" />
		<object type=\"application/x-shockwave-flash\" data=\"/swf/player.swf\" width=\"$width\" height=\"$height\">
			<param name=\"movie\" value=\"/swf/player-viral.swf\" />
			<param name=\"allowfullscreen\" value=\"true\" />
			<param name=\"allowscriptaccess\" value=\"always\" />
            <param name=\"wmode\" value=\"transparent\" />
			<param name=\"flashvars\" value=\"file=$videoUrl&image=$previewUrl&skin=/swf/modieus.swf\" />
			<p><a href=\"http://get.adobe.com/flashplayer\">Get Flash</a> to see this player.</p>
		</object>
	</object>";
    
	return $html;
}

function makeVideoThumbnailUrl($clipId, $version=0) {
    // return "http://i.ytimg.com/vi/u5h6sfgTne4/hqdefault.jpg?w=160&h=120&sigh=eeV45qJBzovmH6kE8Ao-59gZtZY";
    $config = Vega_App::getInstance()->coreConfig;
    $filename = $version ? $clipId . '.jpg?v=' . $version : $clipId . '.jpg';
	return $config['static']['data_url'] . $config['static']['video'] . storageSolutionEncode1($clipId) . '/' . $filename;
}

function makeLargeVideoThumbnailUrl($clipId, $version=0) {
    // return "http://i.ytimg.com/vi/u5h6sfgTne4/hqdefault.jpg?w=160&h=120&sigh=eeV45qJBzovmH6kE8Ao-59gZtZY";
    $config = Vega_App::getInstance()->coreConfig;
    $filename = $version ? $clipId . '.jpg?v=' . $version : $clipId . '_large.jpg';
	return $config['static']['data_url'] . $config['static']['video'] . storageSolutionEncode1($clipId) . '/' . $filename;
}

function makeVideoCatThumbnailUrl($id, $version) {
    $config = Vega_App::getInstance()->coreConfig;
    $filename = $version ? $id . '.jpg?v=' . $version : $id . '.jpg';
    return $config['static']['data_url'] . $config['static']['videocat'] . "/$filename";
}


function storageSolutionEncode1($objID, $isDir = false) {
	$step   		= 15;	//so bit de ma hoa ten thu muc tren 1 cap
	$layer  		= 3;	//so cap thu muc
	$max_bits 		= PHP_INT_SIZE*8;
	$result 		= "";

	for($i=$layer; $i>0; $i--)
	{
   		$shift   = $step*$i;
		$layer_name  = $shift<=$max_bits?$objID >> $shift:0;

	   	$result .= $isDir ? DS.$layer_name : "/".$layer_name;
	}

	return $result;
}

function sec2time($sec)
{
	$hour = floor($sec / 3600);
	$min = floor(($sec - $hour * 3600) / 60);
    $second = $sec - $hour*3600 - $min*60;
	return "$hour:$min:$second";
}

function isAdmin()
{
    return (isset($_SESSION['abbr']) && $_SESSION['abbr'] == 'admin');
}

function rand_array($list)
{
	$newList = array();
	while($list)
	{
		$randKey = array_rand($list, 1);
		$item = $list[$randKey];
		$newList[] = $item;
		unset($list[$randKey]);
	}
	
	return $newList;
}